﻿using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using BLO;
using DTO;

namespace QuanLyBanHang
{
    public partial class frmHangHoa : Form
    {
        private readonly SanPham_Blo _sanPhamBlo = new SanPham_Blo();
        private string _filePath, _field, _valueField;

        public frmHangHoa()
        {
            InitializeComponent();
        }

        private void btnDong_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            _filePath = openFileDialog1.FileName;
            openFileDialog1.Filter = "Image file (*.jpg)|*.jpg|Image file (*.png)|*.png|All file (*.*)|*.*";
            txtImageUrl.Text = File.Exists(_filePath) ? _filePath : @"../../images/default.jpg";
            pbHinhAnh.ImageLocation = txtImageUrl.Text;
        }

      
        private void frmHangHoa_Load(object sender, EventArgs e)
        {
            cbbTieuChi.SelectedIndex = 0;
            
            var chatLieuBlo = new ChatLieu_Blo();
            Utility.ComboboxUlt.LoadData(chatLieuBlo.GetAllObject(), cbbChatLieu, 
                new[] { "TenChatLieu", "MaChatLieu" }, "Chọn chất liệu"); 

            var mauSacBlo = new MauSac_Blo();
            Utility.ComboboxUlt.LoadData(mauSacBlo.GetAllObject(), cbbMaMau, 
                new[] { "TenMau", "MaMau" }, "Chọn mã màu"); 
            
            var nuocSxBlo = new NuocSX_Blo();
            Utility.ComboboxUlt.LoadData(nuocSxBlo.GetAllObject(), cbbNuoc, 
                new[] { "TenNuoc", "MaNuoc"}, "Chọn nước sản xuất");

            var loaiBlo = new Loai_Blo();
            Utility.ComboboxUlt.LoadData(loaiBlo.GetAllObject(), cbbLoai,
                  new[] { "TenLoai", "MaLoai" }, "Chọn loại hàng");

            LoadData(); 

            pbHinhAnh.ImageLocation = @"../../images/default.jpg";
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            string msg = "";
            int result = 0;

            string maChatLieu = cbbChatLieu.SelectedValue.ToString();
            string maLoai = cbbLoai.SelectedValue.ToString();
            string maNuoc = cbbNuoc.SelectedValue.ToString();
            string maMau = cbbMaMau.SelectedValue.ToString();

            string dynamicPath = "../../images/" + openFileDialog1.SafeFileName;
            string defaultImgPath = "../../images/default.jpg";

            if (string.IsNullOrEmpty(maChatLieu) || string.IsNullOrEmpty(maLoai) || string.IsNullOrEmpty(maNuoc) ||
                string.IsNullOrEmpty(maMau))
            {
                MessageBox.Show("Bạn phải lựa chọn giá trị của các loại mã!");
                return;
            }

            if (string.IsNullOrEmpty(txtMaHang.Text))
            {
                result = _sanPhamBlo.AddObject(new SanPham_Dto
                                                   {
                                                       GiaBan = decimal.Parse(txtDonGiaBan.Text),
                                                       GiaNhap = decimal.Parse(txtDonGiaNhap.Text),
                                                       MaSP =
                                                           "SP" + _sanPhamBlo.AutoIncrementIdObject(),
                                                       TenSP = txtTenHang.Text.Trim(),
                                                       MaLoai = maLoai,
                                                       MaNuoc = maNuoc,
                                                       MaChatLieu = maChatLieu,
                                                       MaMau = maMau,
                                                       HinhAnh = File.Exists(_filePath) ? dynamicPath : defaultImgPath
                                                   });

                msg = result > 0 ? "Thêm sản phẩm thành công!" : "Thêm sản phẩm không thành công!";
                MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK,
                                result > 0 ? MessageBoxIcon.Information : MessageBoxIcon.Error);

                if (File.Exists(_filePath) && !File.Exists(dynamicPath))
                {
                    Image image = Image.FromFile(_filePath);
                    image.Save(dynamicPath);
                }
                if (result > 0) { 
                    LoadData();
                    SetEnableInput(false);
                    btnThem.Enabled = true;
                    btnLuu.Enabled = false;
                    btnBoQua.Enabled = false;
                }
                
            }
            else
            {
                string masp = txtMaHang.Text.Trim();
                result = _sanPhamBlo.EditObject(masp, new SanPham_Dto()
                {
                    GiaBan = decimal.Parse(txtDonGiaBan.Text),
                    GiaNhap = decimal.Parse(txtDonGiaNhap.Text),
                    MaSP = masp,                        
                    TenSP = txtTenHang.Text.Trim(),
                    MaLoai = maLoai,
                    MaNuoc = maNuoc,
                    MaChatLieu = maChatLieu,
                    MaMau = maMau,
                    HinhAnh = File.Exists(_filePath) ? dynamicPath : defaultImgPath
                });
                msg = result > 0 ? "Cập nhập sản phẩm thành công!" : "Cập nhập sản phẩm không thành công!";
                MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK,
                                result > 0 ? MessageBoxIcon.Information : MessageBoxIcon.Error);

                if (result > 0) { 
                    LoadData();
                    SetEnableInput(false);
                    btnThem.Enabled = true;
                    btnLuu.Enabled = false;
                    btnBoQua.Enabled = false;
                }
            }
            
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            SetEnableInput(true);
            ResetValue();
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
            btnLuu.Enabled = true;
            btnBoQua.Enabled = true;
            btnThem.Enabled = false;
        }

        private void btnHienThiDS_Click(object sender, EventArgs e)
        {
            
        }

        private void dgvHangHoa_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvHangHoa.Rows[e.RowIndex].Cells[0].Value == null || txtTenHang.Enabled) return;
            txtMaHang.Text = dgvHangHoa.Rows[e.RowIndex].Cells["MaSP"].Value.ToString();
            txtTenHang.Text = dgvHangHoa.Rows[e.RowIndex].Cells["TenSP"].Value.ToString();
            cbbLoai.SelectedValue = dgvHangHoa.Rows[e.RowIndex].Cells["MaLoai"].Value.ToString();
            cbbNuoc.SelectedValue = dgvHangHoa.Rows[e.RowIndex].Cells["MaNuoc"].Value.ToString();
            cbbChatLieu.SelectedValue = dgvHangHoa.Rows[e.RowIndex].Cells["MaChatLieu"].Value.ToString();
            txtDonGiaNhap.Text = dgvHangHoa.Rows[e.RowIndex].Cells["GiaNhap"].Value.ToString();
            txtDonGiaBan.Text = dgvHangHoa.Rows[e.RowIndex].Cells["GiaBan"].Value.ToString();
            txtSoLuong.Text = dgvHangHoa.Rows[e.RowIndex].Cells["SoLuong"].Value.ToString();
            cbbMaMau.SelectedValue = dgvHangHoa.Rows[e.RowIndex].Cells["MaMau"].Value.ToString();
            pbHinhAnh.ImageLocation = dgvHangHoa.Rows[e.RowIndex].Cells["HinhAnh"].Value.ToString();

            SetEnableInput(false);
            btnXoa.Enabled = true;
            btnSua.Enabled = true;
        }

        private void LoadData()
        {
            dgvHangHoa.DataSource = _sanPhamBlo.GetAllObject();
            dgvHangHoa.Columns["MaSP"].HeaderText = "Mã sản phẩm";
            dgvHangHoa.Columns["TenSP"].HeaderText = "Tên sản phẩm";
            dgvHangHoa.Columns["MaLoai"].HeaderText = "Mã loại";
            dgvHangHoa.Columns["MaChatLieu"].HeaderText = "Mã chất liệu";
            dgvHangHoa.Columns["GiaNhap"].HeaderText = "Giá nhập";
            dgvHangHoa.Columns["GiaBan"].HeaderText = "Giá bán";
            dgvHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
            dgvHangHoa.Columns["MaMau"].HeaderText = "Mã màu";
            dgvHangHoa.Columns["HinhAnh"].HeaderText = "Hình ảnh";
            dgvHangHoa.Columns["MaNuoc"].HeaderText = "Mã nước";
        }

        private void SetEnableInput(bool b)
        {
            txtTenHang.Enabled = b;
            cbbChatLieu.Enabled = b;
            cbbMaMau.Enabled = b;
            cbbNuoc.Enabled = b;
            cbbLoai.Enabled = b;
            btnOpen.Enabled = b;
        }

        private void ResetValue()
        {
            txtMaHang.Text = "";
            txtTenHang.Text = "";
            cbbLoai.SelectedIndex = 0;
            cbbChatLieu.SelectedIndex = 0;
            cbbMaMau.SelectedIndex = 0;
            cbbNuoc.SelectedIndex = 0;
            btnOpen.Enabled = true;
            txtSoLuong.Text = "0";
            txtDonGiaNhap.Text = "0";
            txtDonGiaBan.Text = "0";
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMaHang.Text.Trim())) return;

            btnXoa.Enabled = false;
            btnThem.Enabled = false;
            SetEnableInput(true);
            btnBoQua.Enabled = true;
            btnLuu.Enabled = true;
            btnSua.Enabled = false;
        }

        private void btnBoQua_Click(object sender, EventArgs e)
        {
            btnBoQua.Enabled = false;
            SetEnableInput(false);
            if (btnThem.Enabled.Equals(false))
            {
                btnThem.Enabled = true;
                btnLuu.Enabled = false;
                return;
            }
            LoadData();
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            int result = _sanPhamBlo.DeleteObject(txtMaHang.Text);
            string msg = "";
            DialogResult dr = MessageBox.Show("Bạn muốn xóa sản phẩm này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                msg = result > 0 ? "Xóa sản phẩm thành công!" : "Xóa sản phẩm thất bại!";
                
            }
            MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK,
                               result > 0 ? MessageBoxIcon.Information : MessageBoxIcon.Error);
            if (result < 0) return;

            LoadData();
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            _valueField =  string.IsNullOrEmpty(txtKeyword.Text) ? cbbTemp.SelectedValue.ToString() : txtKeyword.Text;
            _field += string.Format("='{0}'", _valueField);

            dgvHangHoa.DataSource = _sanPhamBlo.FindObject(_field);
            btnTimKiem.Enabled = false;
            cbbTemp.Enabled = false;
            cbbTemp.DataSource = null;
            cbbTieuChi.SelectedIndex = 0;
        }

       

        private void cbbTieuChi_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbbTieuChi.SelectedItem.ToString())
            {
                case "Loại":
                    btnTimKiem.Enabled = true;
                    cbbTemp.Enabled = true;
                    txtKeyword.Enabled = false;
                    var loaiBlo = new Loai_Blo();
                    Utility.ComboboxUlt.LoadData(loaiBlo.GetAllObject(), cbbTemp,
                          new[] { "TenLoai", "MaLoai" }, "Chọn loại hàng");
                    _field = "MaLoai";
                    break;

                case "Chất liệu":
                    cbbTemp.Enabled = true;
                    txtKeyword.Enabled = false;
                     var chatLieuBlo = new ChatLieu_Blo();
                     Utility.ComboboxUlt.LoadData(chatLieuBlo.GetAllObject(), cbbTemp,
                         new[] { "TenChatLieu", "MaChatLieu" }, "Chọn chất liệu");
                     _field = "MaChatLieu";
                    break;

                case "Số lượng":
                    txtKeyword.Enabled = true;
                    btnTimKiem.Enabled = true;
                    cbbTemp.DataSource = null;
                    cbbTemp.Enabled = false;
                    _field = "SoLuong";
                    break;
                default:
                    btnTimKiem.Enabled = false;
                    txtKeyword.Enabled = false;
                    break;
            }
           
        }

        private void cbbTemp_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnTimKiem.Enabled = !cbbTemp.SelectedIndex.Equals(0);
        }
    }
}